Component({
  properties: {
    currentDate: String,  // 当前选中的日期 YYYY-MM-DD
    maxDate: String      // 最大可选日期（今天）
  },

  data: {
    year: 2025,
    month: 3,
    weekDays: ['一', '二', '三', '四', '五', '六', '日'],
    days: [],
    months: [],
    currentMonth: '3月',
    nextMonth: '4月'
  },

  lifetimes: {
    attached() {
      this.initCalendar()
    }
  },

  methods: {
    initCalendar() {
      // 确保日期格式正确
      const dateStr = this.properties.currentDate || this.properties.maxDate
      const date = new Date(dateStr + 'T00:00:00')  // 添加时间部分以确保正确解析
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      
      this.setData({
        year,
        month,
        currentMonth: `${month}月`,
        nextMonth: `${month + 1}月`
      })
      
      this.generateDays(year, month)
    },

    generateDays(year, month) {
      const days = []
      const firstDay = new Date(year, month - 1, 1)
      const lastDay = new Date(year, month, 0)
      
      // 填充上个月的日期
      const firstDayWeek = firstDay.getDay() || 7
      for (let i = firstDayWeek - 1; i > 0; i--) {
        const date = new Date(year, month - 1, -i + 1)
        days.push({
          day: date.getDate(),
          month: date.getMonth() + 1,
          date: this.formatDate(date),
          isCurrentMonth: false,
          isToday: false,
          disabled: true
        })
      }

      // 填充当月日期
      const maxDate = new Date(this.properties.maxDate + 'T23:59:59')
      for (let i = 1; i <= lastDay.getDate(); i++) {
        const date = new Date(year, month - 1, i)
        const dateStr = this.formatDate(date)
        days.push({
          day: i,
          month,
          date: dateStr,
          isCurrentMonth: true,
          isToday: dateStr === this.formatDate(new Date()),
          disabled: date > maxDate
        })
      }

      // 填充下个月的日期
      const remainingDays = 42 - days.length // 保持6行
      for (let i = 1; i <= remainingDays; i++) {
        const date = new Date(year, month, i)
        days.push({
          day: i,
          month: date.getMonth() + 1,
          date: this.formatDate(date),
          isCurrentMonth: false,
          isToday: false,
          disabled: true
        })
      }

      this.setData({ days })
    },

    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    onDayTap(e) {
      const { date, disabled } = e.currentTarget.dataset
      if (disabled) return
      
      this.triggerEvent('select', { date })
    }
  }
}) 